package com.ruoyi.cms.controller;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.ruoyi.cms.common.BaseController;
import com.ruoyi.cms.domain.*;
import com.ruoyi.cms.exception.*;
import com.ruoyi.cms.service.*;
import com.ruoyi.cms.taglib.ParseEngine;
import com.ruoyi.cms.util.*;
import com.ruoyi.common.annotation.Anonymous;
import com.wf.captcha.ArithmeticCaptcha;
import com.wf.captcha.utils.CaptchaUtil;
import com.ruoyi.common.utils.StringUtils;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@Scope("prototype")
@RequestMapping("/")
public class FrontController extends BaseController {
	@Autowired
	private ArchivesService archivesService;
	@Autowired
	private CategoryService categoryService;
	@Autowired
	private ThemeService themeService;
	@Autowired
	private FormService formService;
	@Autowired
	private FieldService fieldService;
	@Autowired
	private SearchRecordService searchRecordService;
	@Autowired
	private FileConfiguration fileConfiguration;
	@Autowired
	private SystemService systemService;
	@Autowired
	private AttachmentService attachmentService;
	@Autowired
	private ParseEngine parseEngine;

	/**
	 * 首页方法
	 * @throws CmsException
	 * @throws IOException
	 */
    @Anonymous
	@RequestMapping({"","/index"})
	public void index() throws CmsException, IOException {
        com.ruoyi.cms.domain.System system = systemService.getSystem();
		String staticdir = system.getStaticdir();
		if(staticdir.startsWith("/")) {
			staticdir = staticdir.substring(1);
		}
		//如果为静态浏览，则重写向到静态文件
		if(2 == system.getBrowseType()) {
			String url = fileConfiguration.getResourceDir() +"/"+ staticdir + "/index.html";
			File staticFile = new File(url);
			if(!staticFile.exists()) {
				throw new TemplateNotFoundException(
						ExceptionEnum.HTTP_NOT_FOUND.getCode(),
						ExceptionEnum.HTTP_NOT_FOUND.getMessage(),
						"当前浏览方式为静态浏览，您所浏览的静态文件不存在，请先静态化网站后再继续。");
			}
			response.sendRedirect("/" + staticdir + "/index.html");
			return;
		}

		Theme theme = themeService.getCurrentTheme();
		String templatePath = theme.getThemePath() + "/index.html";
		String templateDir = fileConfiguration.getResourceDir() + "/templates/";

		String path = templateDir + templatePath;
		File template = new File(path);
		if(!template.exists()) {
			throw new TemplateNotFoundException(
					ExceptionEnum.TEMPLATE_NOTFOUND_EXCEPTION.getCode(),
					ExceptionEnum.TEMPLATE_NOTFOUND_EXCEPTION.getMessage(),
					"请仔细检查" + template.getAbsolutePath() + "文件，或检查application.yml中的资源目录配置项（web.resource-path）。");
		}
		String newHtml = "";
		try {
			String html = FileUtils.readFileToString(template, "UTF-8");
			newHtml = parseEngine.parse(html);
			outHtml(newHtml);
		} catch (IOException e) {
			throw new TemplateReadException(
					ExceptionEnum.TEMPLATE_READ_EXCEPTION.getCode(),
					ExceptionEnum.TEMPLATE_READ_EXCEPTION.getMessage(),
					"请仔细检查模版文件，或检查application.yml中的资源目录配置项（web.resource-path）。");
		}
	}

	/**
	 * 封面方法
	 * @param typeid 栏目编码
	 * @param visitUrl 访问URL
	 * @throws CmsException
	 * @throws IOException
	 */
	@RequestMapping("cover-{typeid}/{visitUrl}")
	public void cover(@PathVariable String typeid
			, @PathVariable String visitUrl) throws CmsException, IOException {
        com.ruoyi.cms.domain.System system = systemService.getSystem();
		//查询栏目
		Category category = categoryService.queryCategoryByCode(typeid);
		//如果为静态浏览，则重写向到静态文件
		if(2 == system.getBrowseType()) {
			String url = URLUtils.parseURL(system, category, "S");
			String fileUrl = fileConfiguration.getResourceDir() + url;
			File staticFile = new File(fileUrl);
			if(!staticFile.exists()) {
				throw new TemplateNotFoundException(
						ExceptionEnum.HTTP_NOT_FOUND.getCode(),
						ExceptionEnum.HTTP_NOT_FOUND.getMessage(),
						"当前浏览方式为静态浏览，您所浏览的静态文件不存在，请先静态化网站后再继续。");
			}
			response.sendRedirect(url);
			return;
		}

		Theme theme = themeService.getCurrentTheme();
		String templateDir = fileConfiguration.getResourceDir() + "/templates/";
		if(theme == null) {

		}
		if(!visitUrl.startsWith("/")) {
			visitUrl = "/" + visitUrl;
		}
		StringBuffer templatePath = new StringBuffer();
		templatePath.append(theme.getThemePath());

		if(category.getCatModel() == 1) {
			templatePath.append(category.getCoverTemp());
		}else if(category.getCatModel() == 2) {
			templatePath.append(category.getListTemp());
		}else if(category.getCatModel() == 3) {
			templatePath.append(category.getLinkUrl());
		}

		try {
			String path = templateDir + templatePath;
			File template = new File(path);
			if(!template.exists()) {
				throw new TemplateNotFoundException(
						ExceptionEnum.TEMPLATE_NOTFOUND_EXCEPTION.getCode(),
						ExceptionEnum.TEMPLATE_NOTFOUND_EXCEPTION.getMessage(),
						"请仔细检查" + template.getAbsolutePath() + "文件，或检查application.yml中的资源目录配置项（web.resource-path）。");
			}
			String newHtml = "";
			String html = FileUtils.readFileToString(template, "UTF-8");
			newHtml = parseEngine.parse(html);
			newHtml = parseEngine.parseCategory(newHtml,typeid);
			outHtml(newHtml);
		} catch (IOException e) {
			throw new TemplateReadException(
					ExceptionEnum.TEMPLATE_READ_EXCEPTION.getCode(),
					ExceptionEnum.TEMPLATE_READ_EXCEPTION.getMessage(),
					"请仔细检查模版文件，或检查application.yml中的资源目录配置项（web.resource-path）。");
		}
	}

	/**
	 * 列表方法
	 * @param typeid 栏目编码
	 * @param visitUrl 访问URL
	 * @param pageNum 当前页
	 * @param pageSize 分页大小
	 * @throws CmsException
	 * @throws IOException
	 */
	@RequestMapping("list-{typeid}/{visitUrl}/{pageNum}/{pageSize}")
	public void list(@PathVariable String typeid
			, @PathVariable String visitUrl
			, @PathVariable Integer pageNum
			, @PathVariable Integer pageSize) throws CmsException, IOException {
        com.ruoyi.cms.domain.System system = systemService.getSystem();
		String staticdir = system.getStaticdir();
		if(staticdir.startsWith("/")) {
			staticdir = staticdir.substring(1);
		}
		//查询栏目
		Category category = categoryService.queryCategoryByCode(typeid);
		//如果为静态浏览，则重写向到静态文件
		if(2 == system.getBrowseType()) {
			String url = staticdir + URLUtils.parseFileName(category, pageNum);
			String fileUrl = fileConfiguration.getResourceDir() + url;
			File staticFile = new File(fileUrl);
			if(!staticFile.exists()) {
				throw new TemplateNotFoundException(
						ExceptionEnum.HTTP_NOT_FOUND.getCode(),
						ExceptionEnum.HTTP_NOT_FOUND.getMessage(),
						"当前浏览方式为静态浏览，您所浏览的静态文件不存在，请先静态化网站后再继续。");
			}
			response.sendRedirect("/" + url);
			return;
		}

		Theme theme = themeService.getCurrentTheme();
		String templateDir = fileConfiguration.getResourceDir() + "/templates/";
		if(theme == null) {

		}
		if(!visitUrl.startsWith("/")) {
			visitUrl = "/" + visitUrl;
		}
		StringBuffer templatePath = new StringBuffer();
		templatePath.append(theme.getThemePath());

		if(category.getCatModel() == 1) {
			templatePath.append(category.getCoverTemp());
		}else if(category.getCatModel() == 2) {
			templatePath.append(category.getListTemp());
		}else if(category.getCatModel() == 3) {
			templatePath.append(category.getLinkUrl());
		}
		try {
			String path = templateDir + templatePath;
			File template = new File(path);
			if(!template.exists()) {
				throw new TemplateNotFoundException(
						ExceptionEnum.TEMPLATE_NOTFOUND_EXCEPTION.getCode(),
						ExceptionEnum.TEMPLATE_NOTFOUND_EXCEPTION.getMessage(),
						"请仔细检查" + template.getAbsolutePath() + "文件，或检查application.yml中的资源目录配置项（web.resource-path）。");
			}
			String newHtml = "";
			String html = FileUtils.readFileToString(template, "UTF-8");
			newHtml = parseEngine.parse(html);
			newHtml = parseEngine.parseCategory(newHtml, typeid);
			newHtml = parseEngine.parsePageList(newHtml, typeid, pageNum, pageSize);
			outHtml(newHtml);
		} catch (IOException e) {
			throw new TemplateReadException(
					ExceptionEnum.TEMPLATE_READ_EXCEPTION.getCode(),
					ExceptionEnum.TEMPLATE_READ_EXCEPTION.getMessage(),
					"请仔细检查模版文件，或检查application.yml中的资源目录配置项（web.resource-path）。");
		}
	}

	/**
	 * 文章详情方法
	 * @param id 文章ID
	 * @throws CmsException
	 * @throws IOException
	 */
	@RequestMapping("/article/{id}")
	public void article(@PathVariable String id) throws CmsException, IOException{
        com.ruoyi.cms.domain.System system = systemService.getSystem();
		String staticdir = system.getStaticdir();
		if(staticdir.startsWith("/")) {
			staticdir = staticdir.substring(1);
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		Archives archives = archivesService.selectByPrimaryKey(id);
		//如果为静态浏览，则重写向到静态文件
		if(2 == system.getBrowseType()) {
			Category temp = null;
			if(!"-1".equals(archives.getCategoryId())) {
				temp = categoryService.selectById(archives.getCategoryId());
			}else {//顶级分类走该模版
				temp = new Category();
				temp.setId("-1");
				temp.setCnname("顶级分类");
			}
			String catDir = URLUtils.getCategoryDir(temp);

			Date createTime = archives.getCreateTime();
			String dateDir = sdf.format(createTime);

			File staticFile = new File(fileConfiguration.getResourceDir() + staticdir + catDir + "/" + dateDir + "/" + archives.getId() + ".html");
			if(!staticFile.exists()) {
				throw new TemplateNotFoundException(
						ExceptionEnum.HTTP_NOT_FOUND.getCode(),
						ExceptionEnum.HTTP_NOT_FOUND.getMessage(),
						"当前浏览方式为静态浏览，您所浏览的静态文件不存在，请先静态化网站后再继续。");
			}
			response.sendRedirect("/" + system.getStaticdir() + catDir + "/" + dateDir + "/" + archives.getId() + ".html");
			return;
		}


		StringBuffer templatePath = new StringBuffer();
		Theme theme = themeService.getCurrentTheme();
		String templateDir = fileConfiguration.getResourceDir() + "/templates/";
		if(theme == null) {

		}
		templatePath.append(theme.getThemePath());


		Category category = null;
		if(!"-1".equals(archives.getCategoryId())) {
			category = categoryService.selectById(archives.getCategoryId());
			//构建路径
			templatePath.append("/" + category.getArticleTemp());
		}else {//顶级分类走该模版
			templatePath.append("/article.html");
			category = new Category();
			category.setId("-1");
			category.setCnname("顶级分类");
		}
		try {
			String path = templateDir + templatePath;
			File template = new File(path);
			if(!template.exists()) {
				throw new TemplateNotFoundException(
						ExceptionEnum.TEMPLATE_NOTFOUND_EXCEPTION.getCode(),
						ExceptionEnum.TEMPLATE_NOTFOUND_EXCEPTION.getMessage(),
						"请仔细检查" + template.getAbsolutePath() + "文件，或检查application.yml中的资源目录配置项（web.resource-path）。");
			}
			String newHtml = "";
			String html = FileUtils.readFileToString(template, "UTF-8");
			newHtml = parseEngine.parse(html);
			newHtml = parseEngine.parseCategory(newHtml, category.getCode());
			newHtml = parseEngine.parseArticle(newHtml, id);
			newHtml = parseEngine.parsePrevAndNext(newHtml, id);

			//更新点击数
			Archives temp = new Archives();
			temp.setId(id);
			temp.setClicks(archives.getClicks() + 1);
			archivesService.update(temp);

			//输出HTML
			outHtml(newHtml);
		} catch (IOException e) {
			throw new TemplateReadException(
					ExceptionEnum.TEMPLATE_READ_EXCEPTION.getCode(),
					ExceptionEnum.TEMPLATE_READ_EXCEPTION.getMessage(),
					"请仔细检查模版文件，或检查application.yml中的资源目录配置项（web.resource-path）。");
		}
	}

	/**
	 * 附件下载
	 * @param id
	 * @throws AdminGeneralException
	 */
	@RequestMapping("/download/{id}")
	public void download(@PathVariable String id) throws AdminGeneralException {
		try {
            com.ruoyi.cms.domain.System system = systemService.getSystem();
			Attachment attachment = attachmentService.queryAttachmentById(id);
		    //设置响应头和客户端保存文件名
		    response.setCharacterEncoding("utf-8");
		    response.setContentType("multipart/form-data");
		    response.setHeader("Content-Disposition", "attachment;fileName=" + attachment.getFilename());
	        //打开本地文件流
		    String filePath = fileConfiguration.getResourceDir() + system.getUploaddir() + "/" + attachment.getFilepath();
	        InputStream inputStream = new FileInputStream(filePath);
	        //激活下载操作
	        OutputStream os = response.getOutputStream();
	        //循环写入输出流
	        byte[] b = new byte[1024];
	        int length;
	        while ((length = inputStream.read(b)) > 0) {
	            os.write(b, 0, length);
	        }

	        // 这里主要关闭。
	        os.close();
	        inputStream.close();
		}catch (Exception e) {
			throw new AdminGeneralException(
					ExceptionEnum.HTTP_INTERNAL_SERVER_ERROR.getCode(),
					ExceptionEnum.HTTP_INTERNAL_SERVER_ERROR.getMessage(),
					e.getMessage());
		}
	}

	/**
	 * 搜索
	 * @param model
	 * @param params
	 * @throws CmsException
	 */
	@RequestMapping(value = "/search")
	public void search(Model model, SearchEntity params) throws CmsException {
        com.ruoyi.cms.domain.System system = systemService.getSystem();
		StringBuffer templatePath = new StringBuffer();
		Theme theme = themeService.getCurrentTheme();
		String templateDir = fileConfiguration.getResourceDir() + "/templates/";
		if(theme == null) {

		}
		templatePath.append(theme.getThemePath());
		templatePath.append("/search.html");

		if(params.getPageNum() == null)
			params.setPageNum(1);
		if(params.getPageSize() == null)
			params.setPageSize(10);

		try {
			Map<String, Object> entity = params.getEntity();
			if(entity == null || entity.size() <= 0) {
				throw new FormParameterException(
						ExceptionEnum.FORM_PARAMETER_EXCEPTION.getCode(),
						ExceptionEnum.FORM_PARAMETER_EXCEPTION.getMessage(),
						"请仔细检查Form表单参数结构，正确参数格式应该包含entity['keywords']、pageNum、pageSize。");
			}
			String keywords = "";
			if(entity.containsKey("keywords")) {
				keywords = params.getEntity().get("keywords").toString();

				if(keywords.getBytes("GBK").length < 3) {
					throw new FormParameterException(
							ExceptionEnum.FORM_PARAMETER_EXCEPTION.getCode(),
							ExceptionEnum.FORM_PARAMETER_EXCEPTION.getMessage(),
							"搜索关键字不能少于5个字符，请重新输入后进行搜索。");
				}
			}

			String path = templateDir + templatePath;
			File template = new File(path);
			if(!template.exists()) {
				throw new TemplateNotFoundException(
						ExceptionEnum.TEMPLATE_NOTFOUND_EXCEPTION.getCode(),
						ExceptionEnum.TEMPLATE_NOTFOUND_EXCEPTION.getMessage(),
						"请仔细检查" + template.getAbsolutePath() + "文件，或检查application.yml中的资源目录配置项（web.resource-path）。");
			}
			String newHtml = "";
			String html = FileUtils.readFileToString(template, "UTF-8");
			//如果为静态浏览，则生成页面
			if(2 == system.getBrowseType()) {
				newHtml = parseEngine.generate(html);
			}else {
				newHtml = parseEngine.parse(html);
			}
			newHtml = parseEngine.parsePageList(newHtml, params);

			//记录搜索关键词
			SearchRecord sr = new SearchRecord();
			sr.setId(IdUtil.getSnowflake().nextIdStr());
			sr.setKeywords(keywords);
			sr.setCreateTime(new Date());
			searchRecordService.add(sr);

			//输出HTML
			outHtml(newHtml);
		} catch (IOException e) {
			throw new TemplateReadException(
					ExceptionEnum.TEMPLATE_READ_EXCEPTION.getCode(),
					ExceptionEnum.TEMPLATE_READ_EXCEPTION.getMessage(),
					"请仔细检查模版文件，或检查application.yml中的资源目录配置项（web.resource-path）。");
		}
	}

	/**
	 * 前端投稿
	 * @param model
	 * @param params
	 * @return
	 * @throws CmsException
	 */
	@ResponseBody
	@RequestMapping(value = "/input",method = RequestMethod.POST)
	public ResponseResult input(Model model, @RequestParam Map<String,Object> params) throws CmsException {
		// 验证码校验
		if(!params.containsKey("captcha") || StringUtils.isBlank(""+params.get("captcha"))) {
			return ResponseResult.Factory.newInstance(Boolean.FALSE, ExceptionEnum.FORM_PARAMETER_EXCEPTION.getCode(), null, "缺少验证码参数，请添加该参数后重试。");
		}
		if(!CaptchaUtil.ver(params.get("captcha").toString(), request)) {
			return ResponseResult.Factory.newInstance(Boolean.FALSE, ExceptionEnum.FORM_PARAMETER_EXCEPTION.getCode(), null, "验证码输入错误或已超时，请仔细检查后再试。");
		}
		if(!params.containsKey("typeid") || StringUtils.isBlank(""+params.get("typeid"))) {
			return ResponseResult.Factory.newInstance(Boolean.FALSE, ExceptionEnum.FORM_PARAMETER_EXCEPTION.getCode(), null, "缺少[typeid]参数，请添加该参数后重试。");
		}
		if(!params.containsKey("formkey") || StringUtils.isBlank(""+params.get("formkey"))) {
			return ResponseResult.Factory.newInstance(Boolean.FALSE, ExceptionEnum.FORM_PARAMETER_EXCEPTION.getCode(), null, "缺少[formkey]参数，请添加该参数后重试。");
		}

		// 清除验证码
		CaptchaUtil.clear(request);

		String typeid = params.get("typeid").toString();
		String formkey = params.get("formkey").toString();

		Category categoryWithBLOBs = categoryService.queryCategoryByCode(typeid);
		if(categoryWithBLOBs == null) {
			return ResponseResult.Factory.newInstance(Boolean.FALSE, ExceptionEnum.FORM_PARAMETER_EXCEPTION.getCode(), null, "栏目不存在，请仔细检查[typeid]参数是否有误，核实后重试。");
		}

		if(categoryWithBLOBs.getIsInput() != 1) {
			return ResponseResult.Factory.newInstance(Boolean.FALSE, ExceptionEnum.FORM_PARAMETER_EXCEPTION.getCode(), null, "栏目不允许投稿，请仔细检查栏目的详情并设置是否允许投稿为是后重试。");
		}

		Form form = formService.queryFormByCode(formkey);
		if(form == null) {
			return ResponseResult.Factory.newInstance(Boolean.FALSE, ExceptionEnum.FORM_PARAMETER_EXCEPTION.getCode(), null, "表单模型不存在，请仔细检查[formkey]参数是否有误，核实后重试。");
		}

		Archives archives = new Archives();
		archives.setId(IdUtil.getSnowflake().nextIdStr());
		archives.setCreateTime(new Date());
		archives.setStatus(1);//未发布

		archives.setTitle(StringUtils.isBlank(""+params.get("title")) ? "" : params.get("title").toString());
		archives.setTag(StringUtils.isBlank(""+params.get("tag")) ? "" : params.get("tag").toString());
		archives.setCategoryId(categoryWithBLOBs.getId());
		archives.setCategoryIds(categoryWithBLOBs.getCatSeq());
		archives.setImagePath(StringUtils.isBlank(""+params.get("imagePath")) ? "" : params.get("imagePath").toString());
		archives.setWeight(StringUtils.isBlank(""+params.get("weight")) ? 0 : Integer.parseInt(params.get("weight").toString()));
		archives.setClicks(StringUtils.isBlank(""+params.get("clicks")) ? 0 : Integer.parseInt(params.get("clicks").toString()));
		archives.setDescription(StringUtils.isBlank(""+params.get("description")) ? "" : params.get("description").toString());
		archives.setComment(StringUtils.isBlank(""+params.get("comment")) ? 0 : Integer.parseInt(params.get("comment").toString()));
		archives.setSubscribe(StringUtils.isBlank(""+params.get("subscribe")) ? 0 : Integer.parseInt(params.get("subscribe").toString()));


		List<Field> fields = fieldService.queryFieldByFormId(form.getId());
		Map<String,Object> additional = new LinkedHashMap<String,Object>();
		additional.put("id", IdUtil.getSnowflake().nextIdStr());
		additional.put("aid", archives.getId());
		for(int i = 0;i < fields.size();i++) {
			Field field = fields.get(i);
			additional.put(field.getFieldName(), params.get(field.getFieldName()));
			//用MAP接收参数，checkbox需要特殊处理
			if("checkbox".equals(field.getDataType())) {
				String[] arr = request.getParameterValues(field.getFieldName());
				if(arr != null && arr.length > 0) {
					StringBuffer checkboxVal = new StringBuffer();
					for (String string : arr) {
						checkboxVal.append(string + ",");
					}
					additional.put(field.getFieldName(), checkboxVal.substring(0, checkboxVal.length() - 1));
				}
			}
		}
		String tableName = "system_" + form.getTableName();

		try {
			archivesService.save(archives,tableName,additional);
		} catch (TransactionException e) {
			return ResponseResult.Factory.newInstance(Boolean.TRUE, ExceptionEnum.HTTP_INTERNAL_SERVER_ERROR.getCode(), null, ExceptionEnum.HTTP_INTERNAL_SERVER_ERROR.getMessage());
		}

		return ResponseResult.Factory.newInstance(Boolean.TRUE, StateCodeEnum.HTTP_SUCCESS.getCode(), null, StateCodeEnum.HTTP_SUCCESS.getDescription());
	}

	@RequestMapping("sitemap.xml")
	public void sitemap() throws IOException {
		com.ruoyi.cms.domain.System system = systemService.getSystem();

		Map<String, Object> entity = new HashMap<>();
		entity.put("isShow", "1");
		entity.put("parentId", "-1");
		List<Category> list = categoryService.getTreeList(entity);

		StringBuilder xml = new StringBuilder();

		xml.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>")
		   .append("<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd\">");
		xml.append("<url>");
		xml.append("<loc>" + system.getWebsite() + "</loc>");
		xml.append("<priority>" + 1.0 + "</priority>");
		xml.append("<lastmod>" + DateUtil.format(new Date(), "yyyy-MM-dd") + "</lastmod>");
		xml.append("<changefreq>always</changefreq>");
		xml.append("</url>");

		URLUtils.parseSiteMap(system, archivesService, list, xml);

		xml.append("</urlset>");
		HttpServletResponse httpServletResponse = getResponse();
		httpServletResponse.setCharacterEncoding("UTF-8");
		httpServletResponse.setContentType("text/xml;charset=utf-8");
		httpServletResponse.setHeader("Cache-Control", "no-cache");
		httpServletResponse.setHeader("Cache-Control", "no-store");
		httpServletResponse.setHeader("Pragma", "no-cache");
		httpServletResponse.setDateHeader("Expires", 0L);
		httpServletResponse.getWriter().write(xml.toString());
		httpServletResponse.flushBuffer();
	}

	// 产生验证码
	@RequestMapping("getKaptcha")
	public void getKaptcha() throws IOException {
		ArithmeticCaptcha captcha = new ArithmeticCaptcha(130, 48);
        captcha.getArithmeticString();  // 获取运算的公式：3+2=?
        captcha.text();  // 获取运算的结果：5
		CaptchaUtil.out(captcha, request, response);
	}

	/**
	 * 输出字符串到页面
	 */
	public void outHtml(String html) {
		try {
			HttpServletResponse httpServletResponse = getResponse();
			httpServletResponse.setCharacterEncoding("UTF-8");
			httpServletResponse.setContentType("text/html;charset=utf-8");
			httpServletResponse.setHeader("Cache-Control", "no-cache");
			httpServletResponse.setHeader("Cache-Control", "no-store");
			httpServletResponse.setHeader("Pragma", "no-cache");
			httpServletResponse.setDateHeader("Expires", 0L);
			httpServletResponse.getWriter().write(html);
			httpServletResponse.flushBuffer();
		} catch (IOException e) {

		}
	}
}
